<template>
  <view class="content">
    <view class="top marg-btm10">
      <text>正在置换中</text>
      <text class="green">{{ topTotal }}只</text>
    </view>
    <uni-list>
      <uni-list-item>
        <!-- 自定义 body -->
        <template v-slot:body>
          <view class="list">
            <view class="flex1">日期</view>
            <view class="wid1">置换数量</view>
            <view class="wid2">已置换</view>
            <view class="wid1">未被置换</view>
            <view class="wid3">可激活额度</view>
            <view class="wid">操作</view>
          </view>
        </template>
      </uni-list-item>
      <template v-if="list && list.length > 0">
        <uni-list-item v-for="item in list" :key="item.id">
          <!-- 自定义 body -->
          <template v-slot:body>
            <view class="list">
              <view class="flex1">{{ item.created_at }}</view>
              <view class="wid1">{{ item.itemTotal }}</view>
              <view class="wid2">{{ item.itemAdopt }}</view>
              <view class="wid1">{{ item.itemNoAdopt }}</view>
              <view class="wid3">{{ item.itemRelease ?? 0 }}</view>
              <view class="wid">
                <button
                  v-if="(item.itemRelease || 0) > 0"
                  @click="onActivate(item)"
                  type="default"
                  size="mini"
                >
                  激活
                </button>
              </view>
            </view>
          </template>
        </uni-list-item>
      </template>
      <uni-list-item v-else-if="!loading && list.length === 0">
        <!-- 自定义 body -->
        <template v-slot:body>
          <view style="margin: 0 auto"><statusTips></statusTips></view>
        </template>
      </uni-list-item>
    </uni-list>

    <!-- 加载状态 -->
    <view v-if="loading" class="loading-more">
      <text>加载中...</text>
    </view>

    <!-- 加载完成提示 -->
    <view v-if="loadFinished && list.length > 0" class="load-finished">
      <text>数据已经加载完</text>
    </view>

    <!-- 激活弹窗 -->
    <uni-popup ref="popupActive" type="center">
      <view class="active-popup">
        <view class="title">激活</view>
        <view class="row">
          <text>当前已释放数量：</text>
          <text class="value">
            {{ (activeItem && activeItem.itemRelease) || 0 }}
            只
          </text>
        </view>
        <view class="row">
          <text>本次可激活数量：</text>
          <uni-number-box
            :value="activeQty"
            :min="1"
            :max="
              activeItem && activeItem.itemRelease ? activeItem.itemRelease : 1
            "
            :step="1"
            @change="onQtyChange"
          />
        </view>
        <view class="row">
          <text>本次兑换的消费额度：</text>
          <text class="value">{{ activeQty * unitAmount }}元</text>
        </view>
        <view class="tips">
          <view class="tips-title">特别提醒</view>
          <view class="tip">1、一旦激活后，将不能取消；</view>
          <view class="tip">
            2、请先到【换换猫】平台查看能额度消费的商家，以及有您需要的额度商品；
          </view>
          <view class="tip">
            3、激活一只狗，将兑换成{{ unitAmount }}元消费额度；
          </view>
        </view>
        <button class="confirm-btn" @click="confirmActivate">确认激活</button>
      </view>
    </uni-popup>
  </view>
</template>

<script setup lang="ts">
import { ref, nextTick } from "vue";
import { onLoad, onReachBottom } from "@dcloudio/uni-app";
import {
  getNoAdopt,
  cancelLaunch,
  quotaActive,
  getQuotaActiveNum,
} from "@/api/bgame";
import statusTips from "@/components/statusTips/statusTips.vue";
import { useUserStoreHook } from "@/store/user";

const topTotal = ref("0");
const list = ref([]);
const loading = ref(false);
const loadFinished = ref(false);
const currentPage = ref(1);
const lastPage = ref(1);
const popupActive = ref<any>(null);
const activeItem = ref<any>(null);
const activeQty = ref<number>(0);
const unitAmount = ref<number>(7); // 单只额度，暂用假数据，后续改为接口返回

onLoad(async (option) => {
  await useUserStoreHook().getSign();
  setInit();
});

// 触底加载更多
onReachBottom(() => {
  if (
    !loading.value &&
    !loadFinished.value &&
    currentPage.value < lastPage.value
  ) {
    loadMore();
  }
});

const setInit = () => {
  // 重置分页数据
  currentPage.value = 1;
  lastPage.value = 1;
  loadFinished.value = false;
  list.value = [];
  // 新增：获取单位额度
  fetchUnitAmount();
  getGetNoAdopt(true);
};

// 加载更多
const loadMore = () => {
  if (currentPage.value < lastPage.value) {
    currentPage.value++;
    getGetNoAdopt(false);
  }
};

const getGetNoAdopt = async (isInit = false) => {
  if (loading.value) return;

  loading.value = true;

  if (isInit) {
    uni.showLoading({
      title: "获取信息中...",
      mask: true,
    });
  }

  const res: any = await getNoAdopt({ page: currentPage.value });

  loading.value = false;

  if (isInit) {
    uni.hideLoading();
  }

  if (1 == res.result) {
    const {
      noAdopt = 0,
      data = [],
      currentPage: resCurrentPage = 1,
      lastPage: resLastPage = 1,
    } = res.data || {};

    topTotal.value = noAdopt || 0;
    currentPage.value = resCurrentPage;
    lastPage.value = resLastPage;

    if (isInit) {
      list.value = data || [];
    } else {
      const more = data || [];
      list.value = [...list.value, ...more];
    }

    // 判断是否加载完成
    if (currentPage.value >= lastPage.value) {
      loadFinished.value = true;
    }
  }
};

const onSubmit = async (item: any) => {
  uni.showLoading({
    title: "取消中...",
    mask: true,
  });
  const res: any = await cancelLaunch({ bill_no: item.bill_no });

  uni.hideLoading();
  if (1 == res.result) {
    uni.showToast({
      title: "取消成功",
      icon: "none",
    });
    setInit();
  } else {
    uni.showToast({
      title: res.msg.msg || "取消失败",
      mask: true,
      icon: "error",
    });
  }
};

// 对返回的数据增加“已释放”假数据字段
// const addFakeRelease = (it: any) => {
//   const noAdopt = Number(it.itemNoAdopt || 0);
//   const fakeRelease = Math.max(0, Math.floor(noAdopt / 2)); // 假数据规则：未被置换的一半
//   return { ...it, itemRelease: fakeRelease };
// };

const onActivate = (item: any) => {
  activeItem.value = item;
  activeQty.value = item.itemRelease || 0; // 默认赋值为选中行“已释放”数量
  if (activeQty.value <= 0) activeQty.value = 1;
  nextTick(() => {
    if (popupActive.value && typeof popupActive.value.open === "function") {
      popupActive.value.open("center");
    } else {
      console.log("popupActive 未初始化或无 open 方法:", popupActive.value);
      uni.showToast({ title: "弹窗未初始化", icon: "none" });
    }
  });
};

const incQty = () => {
  const max = activeItem.value?.itemRelease || 0;
  if (activeQty.value < max) {
    activeQty.value++;
  }
};

const decQty = () => {
  if (activeQty.value > 1) {
    activeQty.value--;
  }
};

const onQtyChange = (val: any) => {
  const max = activeItem.value?.itemRelease || 1;
  const num = Number(val);
  if (Number.isFinite(num)) {
    activeQty.value = Math.max(1, Math.min(max, num));
  }
};

const confirmActivate = async () => {
  const billNo = activeItem.value?.bill_no;
  const activeNum = Number(activeQty.value || 0);
  if (!billNo) {
    uni.showToast({ title: "缺少批次号", icon: "none" });
    return;
  }
  if (!Number.isFinite(activeNum) || activeNum <= 0) {
    uni.showToast({ title: "请输入正确的激活数量", icon: "none" });
    return;
  }
  uni.showLoading({ title: "激活中...", mask: true });
  const res: any = await quotaActive({
    bill_no: billNo,
    active_num: activeNum,
    user_id: uni.getStorageSync("user_id") || 0,
  });
  uni.hideLoading();
  if (1 == res.result) {
    if (popupActive.value && typeof popupActive.value.close === "function") {
      popupActive.value.close();
    }
    uni.showToast({ title: "激活成功", icon: "none" });
    setInit();
  } else {
    uni.showToast({
      title: (res.msg && (res.msg.msg || res.msg)) || "激活失败",
      icon: "error",
    });
  }
};
const fetchUnitAmount = async () => {
  try {
    const res: any = await getQuotaActiveNum({});
    if (1 == res.result) {
      const { unitAmount: num = 0 } = res.data || {};
      unitAmount.value = Number(num) || 0;
    }
  } catch (e) {
    console.log("获取单位额度失败", e);
  }
};
</script>

<style lang="scss" scoped>
.content {
  width: 100%;
  height: calc(100vh - 44px);
  padding: 8rpx;

  .top {
    display: flex;
    flex-direction: column;
    text-align: center;
    align-items: center;

    .green {
      color: green;
    }

    text {
      padding: 6rpx;
    }
  }
}

.list {
  width: 100%;
  display: flex;
  font-size: 0.8rem;
  .flex1 {
    flex: 1;
    width: 0;
  }

  .wid {
    width: 40px;
    text-align: center;

    button {
      padding: 0 6rpx;
      color: green;
      border: green 1px solid;
    }
  }
  .wid1 {
    width: 55px;
    text-align: center;

    button {
      padding: 0 6rpx;
      color: green;
      border: green 1px solid;
    }
  }
  .wid2 {
    width: 50px;
    text-align: center;

    button {
      padding: 0 6rpx;
      color: green;
      border: green 1px solid;
    }
  }
  .wid3 {
    width: 70px;
    text-align: center;
  }
}

.loading-more {
  text-align: center;
  padding: 20rpx;
  color: #999;
  font-size: 28rpx;
}

.load-finished {
  text-align: center;
  padding: 20rpx;
  color: #999;
  font-size: 28rpx;
}

.greenBtn {
  padding: 0 6rpx;
  color: green;
  border: green 1px solid;
}
.wid100 {
  width: 100px;
}
.marg-btm10 {
  margin-bottom: 10px;
}

.active-popup {
  width: 80vw;
  background: #fff;
  border-radius: 10px;
  padding: 20rpx;

  .title {
    text-align: center;
    font-size: 16px;
    font-weight: 600;
    margin-bottom: 20rpx;
  }

  .row {
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 10rpx 0;

    .value {
      font-weight: 600;
    }

    .counter {
      display: flex;
      align-items: center;

      .btn {
        width: 60rpx;
        height: 60rpx;
        line-height: 60rpx;
        text-align: center;
        border: 1px solid #ddd;
        border-radius: 50%;
        background: #f5f5f5;
      }
      .qty {
        width: 120rpx;
        text-align: center;
        margin: 0 10rpx;
        font-size: 16px;
      }
    }
  }

  .tips {
    background: #f7f7f7;
    border-radius: 8rpx;
    padding: 16rpx;
    margin: 20rpx 0;

    .tips-title {
      font-weight: 600;
      margin-bottom: 8rpx;
    }
    .tip {
      font-size: 14px;
      color: #666;
      line-height: 1.6;
    }
  }

  .confirm-btn {
    width: 100%;
    background: #22c55e;
    color: #fff;
    border: none;
  }
}

.green {
  color: green;
}
</style>
